package ch.bfh.abcmmh.controller.operating.history;

import java.util.ArrayList;
import java.util.Observable;
import java.util.Observer;

import ch.bfh.abcmmh.controller.operating.LogicController;
import ch.bfh.abcmmh.controller.operating.utilities.DAttribute;
import ch.bfh.abcmmh.controller.operating.utilities.StreetSequenceCalulator;
import ch.bfh.abcmmh.model.streetutils.streetattribute.SAttribute;

public class HistoryWriter implements Observer {

	public static int RESULTLENGTH = 500;
	public static int HISTORYMEMORY = 410;

	private LogicController logicController;
	private StreetSequenceCalulator calulator;
	private int streetCount;

	private ArrayList<ArrayList<Integer[]>> allStreets; // 3 Dimensions

	public HistoryWriter(LogicController logicController) {
		this.logicController = logicController;
		this.calulator = new StreetSequenceCalulator(logicController);
		this.streetCount = logicController.getCountofStreets();
		this.allStreets = new ArrayList<ArrayList<Integer[]>>();
		// Initialize the first Dimension (streets)
		for (int i = 0; i < streetCount; i++) {
			ArrayList<Integer[]> street = new ArrayList<Integer[]>();
			allStreets.add(street);
		}
	}

	@Override
	public void update(Observable o, Object arg) {

		for (int i = 0; i < streetCount; i++) {
			SAttribute[] sAttributes = logicController.getStreetGenerator().getStrAttributes(i);
			DAttribute[] sequence = calulator.calculateStreetSequence(RESULTLENGTH, sAttributes, 0,
			        logicController.getStreetlength());

			// create the third dimension (position)
			Integer[] sqs = new Integer[sequence.length];
			for (int j = 0; j < sequence.length; j++) {
				sqs[j] = sequence[j].getHasCar();
			}
			
			// create the second dimension (time)
			allStreets.get(i).add(sqs);
			
			// only memories "HISTORYMEMORY"-length
			if (allStreets.get(i).size() >= HISTORYMEMORY) {
				// remove the oldest one, the others will automatics reordered
				allStreets.get(i).remove(0);
			}
		}
	}

	public ArrayList<ArrayList<Integer[]>> getAllStreets() {
		return allStreets;
	}

}
